#include "Const.h"
#include "Game.h"
#include "Man.h"

/**
 * 构造方法。
 * @param back      背后对象
 * @param bitmap    后台缓冲位图
 * @param gameBoard 游戏区域
 * @param type      类型
 * @param x, y      左上角坐标
 */
Man::Man(BaseGameObject* back,  QPixmap* bitmap, QWidget* gameBoard, Type type, int x, int y) :
    Box(back, bitmap, type, x, y),
    mCurrentImage1(&mImage),
    mCurrentImage2(&mImage2),
    mGameBoard(gameBoard) {
    // 加载所有图片
    mImageLeft1.load(QString(Const::IMAGE_FILE_PATH).arg(type * 10 + 2));
    mImageLeft2.load(QString(Const::IMAGE_FILE_PATH).arg(type * 10 + 3));
    mImageRight1.load(QString(Const::IMAGE_FILE_PATH).arg(type * 10 + 4));
    mImageRight2.load(QString(Const::IMAGE_FILE_PATH).arg(type * 10 + 5));
    mImageUp1.load(QString(Const::IMAGE_FILE_PATH).arg(type * 10 + 6));
    mImageUp2.load(QString(Const::IMAGE_FILE_PATH).arg(type * 10 + 7));

    // 连接信号与槽
    QObject::connect(&mTimer, SIGNAL(timeout()), this, SLOT(dancing()));

    // 开始跳舞
    mTimer.start(Const::TIMER_INIT);
}

/**
 * 析构方法。
 */
Man::~Man() {
    // 停止定时器
    mTimer.stop();
}

/**
 * 跳舞。
 */
void Man::dancing() {
    if (mCurrentImage == mCurrentImage1) {
        mCurrentImage = mCurrentImage2;
    } else {
        mCurrentImage = mCurrentImage1;
    }
    mDrawer.begin(mBitmap);
    mDrawer.drawImage(mX * Const::GRID_SIZE, mY * Const::GRID_SIZE, *mCurrentImage);
    mDrawer.end();
    mGameBoard->update();
}

/**
 * 移动。
 * @param direction     方向
 * @param moveResult    移动结果
 * @return 被推动的箱子
 */
BaseGameObject* Man::move(int direction, MoveResult* moveResult) {
    int destX = mX, destY = mY; // 新位置的坐标

    // 根据方向，计算新位置的坐标和图片
    switch (direction) {
        case Qt::Key_Down:
            destY++;
            mCurrentImage1 = &mImage;
            mCurrentImage2 = &mImage2;
            break;
        case Qt::Key_Left:
            destX--;
            mCurrentImage1 = &mImageLeft1;
            mCurrentImage2 = &mImageLeft2;
            break;
        case Qt::Key_Right:
            destX++;
            mCurrentImage1 = &mImageRight1;
            mCurrentImage2 = &mImageRight2;
            break;
        case Qt::Key_Up:
            destY--;
            mCurrentImage1 = &mImageUp1;
            mCurrentImage2 = &mImageUp2;
            break;
    }

    // 重新设置图片
    mCurrentImage = mCurrentImage1;

    // 先移动旁边的物体
    BaseGameObject* box = Game::sBaseGameObjects[destY][destX]->move(direction, moveResult);
    if (*moveResult == NO_MOVE) {
        return box;
    }

    // 移动小人
    Box::move(direction, moveResult);

    return box;
}
